/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.datastore.database;

import at.schauer.gregor.vienna.datastore.DataStore;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.io.Serializable;
import java.util.List;

/**
 * @author Gregor Schauer
 */
public class HibernateDataStore<T> implements DataStore<T> {
	protected SessionFactory sessionFactory;

	public HibernateDataStore(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <E extends T> E load(Class<E> type, Object identifier) {
		return (E) getSession().load(type, (Serializable) identifier);
	}

	@Override
	public Object save(T obj) {
		return getSession().save(obj);
	}

	@Override
	public void delete(T obj) {
		getSession().delete(obj);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <E extends T> List<E> list(Class<E> type) {
		return getSession().createCriteria(type).list();
	}

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
}
